using System.Net;
using CampusModel;
using CampusModel.Model;
using Microsoft.EntityFrameworkCore;
using PublicProject.PublicClass.ExtensionException;

namespace CampusDataOperationLibrary;

public class StudentOperation(CampusModelDbContext dbContext)
{
    public async Task<List<Course>> GetCoursesAsync(string userId)
    {
        var user = await GetUserByIdAsync(userId);
        var student = await GetStudentByIdAsync(user.UserId);
        var courses = await dbContext.Courses.Include(x => x.Teacher).Where(x => x.ClassId == student.ClassId).ToListAsync();
        return courses;
    }


    private async Task<User> GetUserByIdAsync(string id)
    {
        var userId = int.Parse(id);
        var user = await dbContext.Users.FindAsync(userId) ?? throw new ExceptionWithStatus(HttpStatusCode.NotFound, "用户不存在");
        return user;
    }

    private async Task<Student> GetStudentByIdAsync(int id)
    {
        var student = await dbContext.Students.FindAsync(id) ?? throw new ExceptionWithStatus(HttpStatusCode.NotFound, "学生不存在");
        return student;
    }
    public async Task<bool> SignInAsync(string id, int attendeeId, int layerId)
    {
        var user = await GetUserByIdAsync(id);
        var student = await GetStudentByIdAsync(user.UserId);
        var attendee = await dbContext.AttendanceRecords.Include(x => x.Students).SingleOrDefaultAsync(x => x.AttendanceID == attendeeId) ?? throw new ExceptionWithStatus(HttpStatusCode.NotFound, "签到课程不存在");
        if (attendee.AttendanceLayerID != layerId)
        {
            throw new ExceptionWithStatus(HttpStatusCode.BadRequest, "签到位置错误");
        }
        attendee.Students.Add(student);
        return await dbContext.SaveChangesAsync() > 0;
    }
    public async ValueTask<List<(DateTime, bool )>> GetStudentAttendancesAsync(string id, string courseName)
    {
        var user = await GetUserByIdAsync(id);
        var student = await GetStudentByIdAsync(user.UserId);
        var result = await dbContext.AttendanceRecords.Include(x => x.Students).Include(x => x.Course).Where(x => x.Course.CourseName == courseName).ToListAsync();
        return result.Select(x => (x.AttendanceTime, x.Students.Any(y => y.Id == student.Id))).ToList();
    }
}